/*
 *                    BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 *
 * Created on 15.08.2007
 * @author Asia Grzibovska
 *
 */

package uk.ac.sanger;

import org.xml.sax.*;             // The main SAX package
import java.util.*;               // Hashtable, lists, and so on


public class CoordinateXMLParser extends org.xml.sax.helpers.DefaultHandler {

	Map nameToAttributes;  // Map from name to attributes
	StringBuffer accumulator;// Accumulate text
	String organism; // Remember text
	Attributes my_attributes;
	String [][] coordinates;

	public String [][] getCoordinates(){
		return coordinates;
	}

	// Called at the beginning of parsing.  We use it as an init() method
	public void startDocument() {
		accumulator = new StringBuffer();
		nameToAttributes = new HashMap();
		//coordinates=null;
	}

	// When the parser encounters plain text (not XML elements), it calls
	// this method, which accumulates them in a string buffer.
	// Note that this method may be called multiple times, even with no
	// intervening elements.
	public void characters(char[] buffer, int start, int length) {
		accumulator.append(buffer, start, length);
	}

	// At the beginning of each new element, erase any accumulated text.
	public void startElement(String namespaceURL, String localName,
			String qname, Attributes attributes) {
		accumulator.setLength(0);
		my_attributes=attributes;
	}

	// Take special action when we reach the end of selected elements.
	// Although we don't use a validating parser, this method does assume
	// that the web.xml file we're parsing is valid.
	public void endElement(String namespaceURL, String localName, String qname)
	{

		if (localName.equals("COORDINATES")) {        // Store element name
			organism = accumulator.toString().trim();
			//store list of attributes
			List attributes = (List)nameToAttributes.get(organism);
			if (attributes == null) {
				attributes = new ArrayList();
				//store element
				nameToAttributes.put(organism, attributes);
			}
			if (my_attributes.getLocalName(0) != null)
			{
				for (int i = 0; i < my_attributes.getLength(); i++) {
					attributes.add(my_attributes.getLocalName(i) + " : " + my_attributes.getValue(i)); 
					//String tmp=my_attributes.getValue(i).toString();
					//if(my_attributes.getLocalName(i).equals("uri")){
						
						//System.out.println(tmp.substring(index) + organism);	
					//}
				}
			}
		}    
	}

	// Called at the end of parsing.  Used here to print our results.
	public void endDocument() {
		List OrganismNames = new ArrayList(nameToAttributes.keySet());
		Collections.sort(OrganismNames);
		System.out.println("No of lines : "+ OrganismNames.size() + "\n--------"); 
		int i=0;
		
		coordinates = new String[OrganismNames.size()][];
		for(Iterator iterator = OrganismNames.iterator(); iterator.hasNext();) {
			String name = (String)iterator.next();
			//List attributes = (List)nameToAttributes.get(name);
			//add to list
			//coordinates.add(name);
			
			String URI = nameToAttributes.get(name).toString();

			String URI_1=URI.substring(URI.indexOf("uri"),URI.indexOf(","));
			int index=0;
			//find last "/"
			while (URI_1.indexOf("/",index)>0){						
				index=URI_1.indexOf("/",index);
				index++;
			}
			
			coordinates[i] = new String[2];                // initialize # of cols
						   
			coordinates[i][0] = name;
			coordinates[i][1] = URI_1.substring(index);

			i++;
		}
	}

	// Issue a warning
	public void warning(SAXParseException exception) {
		System.err.println("WARNING: line " + exception.getLineNumber() + ": "+
				exception.getMessage());
	}

	// Report a parsing error
	public void error(SAXParseException exception) {
		System.err.println("ERROR: line " + exception.getLineNumber() + ": " +
				exception.getMessage());
	}

	// Report a non-recoverable error and exit
	public void fatalError(SAXParseException exception) throws SAXException {
		System.err.println("FATAL: line " + exception.getLineNumber() + ": " +
				exception.getMessage());
		throw(exception);
	}
}
